package com.example.communist_app_api.common.security;

import cn.hutool.json.JSONUtil;
import com.example.communist_app_api.config.mq.NoticeTask;
import com.example.communist_app_api.db.dto.PermissionDTO;
import com.example.communist_app_api.db.pojoDto.Organization;
import com.example.communist_app_api.db.pojoDto.User;
import com.example.communist_app_api.service.AuthorizationService;
import com.example.communist_app_api.service.UserOrganizationService;
import com.example.communist_app_api.service.UserService;
import com.example.communist_app_api.util.JwtUtils;
import com.example.communist_app_api.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 登录成功处理
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private UserService userService;
    @Autowired
    private AuthorizationService authorizationService;
    @Autowired
    private UserOrganizationService userOrganizationService;

    @Autowired
    NoticeTask noticeTask;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        String username=authentication.getName(); // 获取用户名

        // 生成jwt token
        String token= JwtUtils.genJwtToken(username);
        //根据用户名字获取用户所有信息
        User currentUser = userService.getUserInfo(username);

        List<PermissionDTO> permissionDTOList = authorizationService.getPermissionByUser(currentUser.getId());
        //System.out.println("permissionDTOList = " + permissionDTOList);
        //System.out.println("currentUser = " + currentUser);
        Organization organization = userOrganizationService.getOrganizationByUserId(currentUser.getId());

        noticeTask.receiveAsync(currentUser.getId()+"");

        outputStream.write(JSONUtil.toJsonStr(R.ok("登录成功").put("authorization",token)
                .put("menuList",permissionDTOList)
                .put("currentUser",currentUser)
                .put("organization",organization)).getBytes("UTF-8"));

        outputStream.flush();
        outputStream.close();
    }
}
